package cn.pugle.base.classloader;


/**
 * 三种内置classLoader
 *
 * @author tzp
 * @since 2018/2/8
 */
public class BuildInClassLoaderTest {
    static {
        System.out.println("BuildInClassLoaderTest static code");
    }
//    private AClass aObj;

    public static void main(String[] args) {
        ClassLoader classLoader = BuildInClassLoaderTest.class.getClassLoader();//sun.misc.Launcher$AppClassLoader
        do {
            System.out.println(classLoader);
            classLoader = classLoader.getParent();
        } while (classLoader != null);
        //sun.misc.Launcher$AppClassLoader@18b4aac2
        //sun.misc.Launcher$ExtClassLoader@7637f22   都是URLClassLoader子类

        System.out.println(Integer.class.getClassLoader());//null

        try {
            Class<?> aClass = BuildInClassLoaderTest.class.getClassLoader().loadClass("cn.pugle.base.classloader.AClass");
            System.out.println(aClass);
            System.out.println(aClass.getClassLoader());//sun.misc.Launcher$AppClassLoader@18b4aac2


            Object o = aClass.newInstance();
            AClass.sm(null);//class中的静态代码何时执行的??
        } catch (Exception e) {
            e.printStackTrace();
        }


        //子肯定能从父里面找class. 父应该不能从子里面找?
        ClassLoader parent = BuildInClassLoaderTest.class.getClassLoader().getParent();
        try {
            Class<?> aClass = parent.loadClass("cn.pugle.base.classloader.BuildInClassLoaderTest");
            System.out.println(aClass);
            System.out.println(aClass.getClassLoader());
        } catch (ClassNotFoundException e) {
            System.out.println("error " + e.getMessage());
        }

        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println("systemcl " + systemClassLoader);
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();//也可以set
        System.out.println("ctxcl: " + contextClassLoader);//在本例中这俩都是appClassLoader

        BuildInClassLoaderTest loaderTest = new BuildInClassLoaderTest();
        loaderTest.test();
    }

    public AClass test() {
        return new AClass();
    }
}
